using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Reflection;

namespace MosziNET.Web.Gallery.Handlers
{
    public abstract class HandlerBase<T> : IHttpHandler
    {
        #region / Private fields /

        private T requestParameters;

        #endregion / Private fields /

        #region / HandlerBase<T> Members /

        /// <summary>
        /// Provides type safe access to the page parameters
        /// </summary>
        protected T RequestParameters
        {
            get
            {
                return this.requestParameters;
            }
            set
            {
                this.requestParameters = value;
            }
        }

        /// <summary>
        /// Loads the request parameters
        /// </summary>
        protected void LoadRequestParameters(HttpContext context)
        {
            Type paramClassType = typeof(T);
            this.RequestParameters = Activator.CreateInstance<T>();

            // loop through all set request parameters
            foreach (string Key in context.Request.Params.Keys)
            {
                // get the corresponding field
                FieldInfo fi;
                if ((fi = paramClassType.GetField(Key)) != null)
                {
                    // ... and try to set it's value
                    try
                    {
                        fi.SetValue(this.RequestParameters,
                            Convert.ChangeType(context.Request[Key], fi.FieldType));
                    }
                    catch (FormatException)
                    {
                        // if the format of the parameter was not correct
                        // then just discard the problem ...
                    }
                }
            }
        }

        #endregion / HandlerBase<T> Members /

        #region / IHttpHandler Members /

        /// <summary>
        /// When overridden in a class, returns whether this class is reusable
        /// </summary>
        public virtual bool IsReusable
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }

        /// <summary>
        /// Loads the request parameters and handles the request
        /// </summary>
        /// <param name="context"></param>
        public virtual void ProcessRequest(HttpContext context)
        {
            // loads the page parameters
            this.LoadRequestParameters(context);
        }

        #endregion / IHttpHandler Members /
    }
}
